package br.ufc.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


public class WrapperResultSet implements InvocationHandler {

	private List<ResultSet> wrappeds;
	private ResultSet current;
	private int index;

	public WrapperResultSet(List<ResultSet> resultsets) {
		this.wrappeds = resultsets;
		this.index = 0;
		this.current = resultsets.get(this.index);

	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		if ("next".equals(method.getName())) {
			return next(method);
		}
		return method.invoke(current, args);
	}

	public Object next(Method method){
		boolean ret;
		try {
			
			do{
				ret = current.next();
				if(ret == true){
					return true;
				}else{
					this.index ++;
					if(index >= wrappeds.size()){
						break;
					}
					this.current = this.wrappeds.get(index);
				}
			}while(true);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static ResultSet createResultSets(List<ResultSet> resultsets) {
		return (ResultSet)(Proxy.newProxyInstance(ResultSet.class.getClassLoader(),
				new Class[] {ResultSet.class},
				new WrapperResultSet(resultsets)));
	}
}
